package basicutil.dynamic;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 对可编译对象的增删改查操作
 */
public class CompileClassFileInfoDAO {
    public static final CompileClassFileInfoDAO INSTANCE = new CompileClassFileInfoDAO();
    private List<CompileClassFileInfo> allData = new ArrayList<>();

    private CompileClassFileInfoDAO() {
        refreshDataByLocalFile();
    }

    public CompileClassFileInfo queryByName(String name) {
        return allData.stream()
                .filter(o -> Objects.equals(o.getName(), name))
                .findFirst().orElse(null);
    }

    public List<CompileClassFileInfo> queryAll() {
        return allData;
    }

    public void refreshDataByLocalFile() {
        InputStream inputStream = CompileClassFileInfoDAO.class.getClassLoader().getResourceAsStream("complieClassCfg.json");
        try {
            JSONObject jsonObject = JSONObject.parseObject(inputStream, JSONObject.class);
            JSONArray data = jsonObject.getJSONArray("single");
            List<CompileClassFileInfo> fileData = data.toJavaList(CompileClassFileInfo.class);
            allData = fileData;
            JSONArray multiData = jsonObject.getJSONArray("multi");
            List<CompileClassFileInfo> multi = multiData.toJavaList(CompileClassFileInfo.class);
            allData.addAll(multi);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
